﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using AppEnvironment.Lib;
using AppEnvironment.Lib.Interfaces;

namespace AppEnvironment.Web
{
    internal class WebCookies : Singleton<WebCookies>, IStateHolderWithExpiry
    {
        private WebCookies()
        {

        }

        #region IStateHolder Members

        public object this[string name]
        {
            get
            {
                if ((HttpContext.Current.Request == null) || (HttpContext.Current.Request.Cookies == null))
                {
                    return null;
                }

                HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
                if (cookie == null)
                {
                    return null;
                }
                return cookie.Value;
            }
            set
            {
                SetCookie(name, value);
            }
        }

        private void SetCookie(string name, object value)
        {
            if (!(value is string))
            {
                throw new Exception("Can only set string values into Cookies");
            }
            SetValue(name, value as string, DateTime.Now.AddDays(1));
        }

        public void SetValue(string name, string value, DateTime expiry)
        {
            if ((HttpContext.Current.Response == null) || (HttpContext.Current.Response.Cookies == null))
            {
                throw new Exception("Cookies object is null at this time");
            }
            HttpContext.Current.Response.Cookies[name].Value = value;
            HttpContext.Current.Response.Cookies[name].Expires = expiry;
        }

        #endregion
    }
}
